package com.wz.controller;

import com.wz.config.Normal;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @program: demo
 * @description: 状态与交易
 * @author: Wangzheng
 * @create: 2020-12-16 17:16
 **/
@RestController
@RequestMapping("/StatusAndTrade")
public class StatusAndTrade {
	
	
	/*
	* 获取用户当前余额信息:
	* http://localhost:8080/StatusAndTrade/getUserBalance
	* */
	@RequestMapping("/getUserBalance")
	public void getUserBalance(){
		Web3j web3j = Web3j.build(new HttpService(Normal.SERVER));
		try {
			String account = web3j.ethAccounts().send().getAccounts().get(0);
			BigInteger balance = web3j.ethGetBalance(account, DefaultBlockParameterName.LATEST).send().getBalance();
			System.out.println(balance);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 获取用户初始余额信息:
	 * http://localhost:8080/StatusAndTrade/getUserInitBalance
	 * */
	@RequestMapping("/getUserInitBalance")
	public void getUserInitBalance(){
		Web3j web3j = Web3j.build(new HttpService(Normal.SERVER));
		try {
			String account = web3j.ethAccounts().send().getAccounts().get(0);
			BigInteger balance = web3j.ethGetBalance(account, DefaultBlockParameterName.EARLIEST).send().getBalance();
			System.out.println(balance);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/*
	 * 获取用户指定余额信息:
	 * http://localhost:8080/StatusAndTrade/getUserAppointBalance
	 * */
	@RequestMapping("/getUserAppointBalance/{num}")
	public void getUserAppointBalance(@PathVariable("num") Integer num){
		Web3j web3j = Web3j.build(new HttpService(Normal.SERVER));
		try {
			String account = web3j.ethAccounts().send().getAccounts().get(0);
			BigInteger balance = web3j.ethGetBalance(account, new DefaultBlockParameterNumber(num)).send().getBalance();
			System.out.println(balance);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	* 货币单位表示与换算
	 * 
	* */
	@RequestMapping("/transformToWei/{num}")
	public void transformToWei(@PathVariable("num") Integer num){
		BigDecimal oneEther = Convert.toWei(String.valueOf(num),Convert.Unit.ETHER);
		System.out.println(oneEther);
	}
	
	
	
	
	
}